<template>
  <div>
    <el-upload v-if="!readOnly" action="#" class="upload-demo" ref="fileUpload" :before-upload='handleBeforeUpload'
      :http-request="uploadFile" :before-remove="beforeRemove">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <div slot="tip" class="el-upload__tip">{{ placeholder }}</div>
      <ul class="el-upload-list el-upload-list--text">
        <li class="el-upload-list__item is-success" v-for="(v, i) in lastFileList" :key="i">
          <div class="el-upload-list__item-name">
            <i class="el-icon-document"></i>{{ v.name }}
          </div>
          <!-- <i class="el-icon-download my-download" @click="downloadFile(v)"></i> -->
          <i class="el-icon-close" @click="deleteFile(v)"></i>
        </li>
      </ul>
    </el-upload>
    <ul v-else class="el-upload-list el-upload-list--text">
      <li class="el-upload-list__item is-success" v-for="(v, i) in lastFileList" :key="i">
        <div class="el-upload-list__item-name">
          <i class="el-icon-document"></i>{{ v.name }}
        </div>
        <!-- <i class="el-icon-download my-download" @click="downloadFile(v)"></i> -->
      </li>
    </ul>
  </div>
</template>
<script>
import { saveAs } from "file-saver";
export default {
  props: {
    //父节点传递的文件集合
    pFileList: {
      typeof: Array,
      default: () => []
    },
    uploadMethod: {
      typeof: Function,
    },
    downloadMethod: {
      typeof: Function,
      default: () => { },
    },
    placeholder: {
      typeof: String,
      default: "请上传excel文件",
    },
    // 限制上传个数
    limit: {
      type: Number,
      default: 1,
    },
    accept: {
      type: Array,
      default: () => []
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    fileHttp: {
      type: String,
      default: GlobalSetting.IotConfig.fileAPIService
    },
    getFileName: {
      typeof: Function,
    },
  },
  data() {
    return {
      lastFileList: [],//编辑的时候已存在的文件
      fileList: [],
      delFileList: [],//需要删除的文件
    };
  },
  components: {},
  computed: {},
  created() {
    this.lastFileList = JSON.parse(JSON.stringify(this.pFileList))
  },
  mounted() { },
  watch: {
    //监听参数中的pFileList变化
    'pFileList': {
      handler(newValue) {
        this.lastFileList = JSON.parse(JSON.stringify(newValue))
      },
      immediate: true,//初次监听即执行
    }
  },
  methods: {
    beforeRemove(file, fileList) {
      this.fileList.forEach((v, index, array) => {
        if (v.name == file.name) {
          array.splice(v, 1)
        }
      })
      // this?.getFileName(this.fileList)
    },
    uploadFile(httpRequest) {
      const _file = httpRequest.file
      this.fileList.push(_file);
    },
    handleBeforeUpload(_file) {
      const suffix = _file.name.split('\.')
      if (this.fileList.length + this.lastFileList.length >= this.limit) {
        this.$notify({
          message: "只能上传" + this.limit + "个文件！",
          type: "error",
          position: "bottom-right",
          duration: 2000,
        });
        return false
      }
      if (this.accept.length > 0 && this.accept.indexOf(suffix[suffix.length - 1]) === -1) {
        this.$notify({
          message: "只能上传" + this.accept.join() + "文件！",
          type: "error",
          position: "bottom-right",
          duration: 2000,
        });
        return false
      }
      // this?.getFileName(suffix)
      return true
    },
    downloadFile(_obj) {
      const _URL = this.fileHttp + _obj.path
      this.downloadMethod(_URL).then(res => {
        //将Blob 对象转换成字符串
        // let reader = new FileReader();
        // reader.readAsText(res.data, 'utf-8');
        // reader.onload = function (e) {
        //   console.info(reader.result);
        // }
        saveAs(res.data, _obj.name);
      })
    },
    deleteFile(obj) {
      //从数组中获取对象的索引
      function getIndexInArr(_arr, _obj) {
        var len = _arr.length;
        for (var i = 0; i < len; i++) {
          if (_arr[i].path == _obj.path) {
            return i;
          }
        }
        return -1;
      };
      this.delFileList.push(obj);
      this.lastFileList.splice(getIndexInArr(this.lastFileList, obj), 1);
    },
    uploadInfo() {
      let _this = this, _names = [];
      const p = new Promise((resolve, reject) => {
        let uploadImg = new FormData()
        if (_this.fileList.length > 0) {
          _this.fileList.forEach(file => {// 因为要上传多个文件，所以需要遍历
            uploadImg.append('file', file, file.name);
            _names.push(file.name)
          })
          _this?.uploadMethod(uploadImg).then(result => {
            if (result.data.code == 0) {
              let _list = []
              result.data.data.forEach((v, i) => {
                _list.push({
                  path: JSON.parse(v),
                  name: _names[i]
                })
              })
              resolve(_list);
            }
          })
        } else {
          resolve(null);
        }
      })
      return p
    },
  }
}
</script>
<style lang="less" scoped>
.my-download {
  position: absolute;
  top: 5px;
  right: 25px;
  cursor: pointer;
  opacity: 0.75;
  color: #606266;
}

::v-deep .el-upload-list__item .my-download {
  display: none;
}

::v-deep .el-upload-list__item:hover .my-download {
  display: inline-block;
}

::v-deep .el-upload-list__item:first-child {
  margin-top: 4px;
}
</style>